package alert

import (
	"bytes"
	"crypto/tls"
	"fmt"
	"net/smtp"
	"strings"
)

// EmailConfig 邮件配置
type EmailConfig struct {
	Host     string   // SMTP服务器地址
	Port     int      // SMTP服务器端口
	Username string   // 发件人邮箱
	Password string   // 发件人密码
	From     string   // 发件人名称
	To       []string // 收件人列表
}

// EmailMessage 邮件消息
type EmailMessage struct {
	Subject     string   // 邮件主题
	Body        string   // 邮件正文
	ContentType string   // 内容类型 (text/plain 或 text/html)
	Attachments []string // 附件路径列表
}

// NewEmailConfig 创建新的邮件配置
func NewEmailConfig(host string, port int, username, password, from string, to []string) *EmailConfig {
	return &EmailConfig{
		Host:     host,
		Port:     port,
		Username: username,
		Password: password,
		From:     from,
		To:       to,
	}
}

// SendEmail 发送邮件
func (c *EmailConfig) SendEmail(msg *EmailMessage) error {
	auth := smtp.PlainAuth("", c.Username, c.Password, c.Host)

	// 设置邮件头
	header := make(map[string]string)
	header["From"] = c.From
	header["To"] = strings.Join(c.To, ",")
	header["Subject"] = msg.Subject
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = msg.ContentType + "; charset=UTF-8"

	// 构建邮件内容
	var emailBody bytes.Buffer
	for k, v := range header {
		emailBody.WriteString(fmt.Sprintf("%s: %s\r\n", k, v))
	}
	emailBody.WriteString("\r\n")
	emailBody.WriteString(msg.Body)

	// 发送邮件
	addr := fmt.Sprintf("%s:%d", c.Host, c.Port)
	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         c.Host,
	}

	conn, err := tls.Dial("tcp", addr, tlsConfig)
	if err != nil {
		return fmt.Errorf("连接SMTP服务器失败: %v", err)
	}
	defer conn.Close()

	client, err := smtp.NewClient(conn, c.Host)
	if err != nil {
		return fmt.Errorf("创建SMTP客户端失败: %v", err)
	}
	defer client.Close()

	if err = client.Auth(auth); err != nil {
		return fmt.Errorf("SMTP认证失败: %v", err)
	}

	if err = client.Mail(c.Username); err != nil {
		return fmt.Errorf("设置发件人失败: %v", err)
	}

	for _, to := range c.To {
		if err = client.Rcpt(to); err != nil {
			return fmt.Errorf("设置收件人失败: %v", err)
		}
	}

	w, err := client.Data()
	if err != nil {
		return fmt.Errorf("准备发送数据失败: %v", err)
	}
	defer w.Close()

	_, err = w.Write(emailBody.Bytes())
	if err != nil {
		return fmt.Errorf("发送邮件内容失败: %v", err)
	}

	return nil
}

// SendAlert 发送报警邮件
func (c *EmailConfig) SendAlert(subject, body string) error {
	msg := &EmailMessage{
		Subject:     subject,
		Body:        body,
		ContentType: "text/plain; charset=UTF-8",
	}
	return c.SendEmail(msg)
}

// SendHTMLAlert 发送HTML格式的报警邮件
func (c *EmailConfig) SendHTMLAlert(subject, body string) error {
	msg := &EmailMessage{
		Subject:     subject,
		Body:        body,
		ContentType: "text/html; charset=UTF-8",
	}
	return c.SendEmail(msg)
}
